package cn.wangsy.zhidao.p20170324;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class CaculatorTest extends JFrame implements ActionListener {

	private JButton plusButton;// 加法
	private JButton minusButton;// 减法
	private JButton multipButton;// 乘法
	private JButton divideButton;// 除法
	private JTextField paramField1;
	private JTextField paramField2;
	private JTextField resultField;

	public CaculatorTest() {

		this.setTitle("计算器");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setBounds(100, 100, 480, 360);
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);

		paramField1 = new JTextField();
		paramField1.setBounds(10, 130, 40, 30);
		contentPane.add(paramField1);

		int x = 80;
		plusButton = new JButton("+");
		plusButton.setBounds(x, 10, 50, 50);
		plusButton.addActionListener(this);
		contentPane.add(plusButton);

		minusButton = new JButton("-");
		minusButton.setBounds(x, 80, 50, 50);
		minusButton.addActionListener(this);
		contentPane.add(minusButton);

		multipButton = new JButton("*");
		multipButton.setBounds(x, 150, 50, 50);
		multipButton.addActionListener(this);
		contentPane.add(multipButton);

		divideButton = new JButton("/");
		divideButton.setBounds(x, 220, 50, 50);
		divideButton.addActionListener(this);
		contentPane.add(divideButton);

		paramField2 = new JTextField();
		paramField2.setBounds(160, 130, 40, 30);
		contentPane.add(paramField2);
		JLabel label3 = new JLabel("=");
		label3.setBounds(210, 130, 40, 30);
		resultField = new JTextField();
		contentPane.add(label3);
		resultField.setBounds(230, 130, 80, 30);
		contentPane.add(resultField);

		this.setContentPane(contentPane);
		this.setVisible(true);
	}

	public static void main(String[] args) {
		CaculatorTest frame = new CaculatorTest();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		Float param1 = 0f;
		Float param2 = 0f;
		try {
			param1 = Float.parseFloat(paramField1.getText().toString());
			param2 = Float.parseFloat(paramField2.getText().toString());
		} catch (NumberFormatException e1) {
			resultField.setText("出错啦");
			return;
		}
		if (e.getSource() == plusButton) {
			resultField.setText(String.valueOf(param1 + param2));
		} else if (e.getSource() == minusButton) {
			resultField.setText(String.valueOf(param1 - param2));
		} else if (e.getSource() == multipButton) {
			resultField.setText(String.valueOf(param1 * param2));
		} else if (e.getSource() == divideButton) {
			if (param2 == 0) {
				resultField.setText("除数不能为0");
			} else {
				resultField.setText(String.valueOf(param1 / param2));
			}
		}
	}

}
